<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>路由守卫 全局</title>
    </head>
    <body>
        <div id='app'>
            <router-link to="/">首页</router-link>
            <router-link to="/about">关于我们</router-link>
            <router-link to="/center">用户中心</router-link>
            <router-link to="/login">登录</router-link>
            <router-view></router-view>
        </div>
        <script src='../js/vue.js'></script>
        <script src="../js/vue-router.js"></script>
        <script>
            var home = {template: `<div>我是首页</div>`}
            var about = {template: `<div>我是 关于我们</div>`}
            var center = {template: `<div>我是用户中心页面</div>`}
            var login = {
                template: `
                  <div>
                  我是登录页
                  <button @click="changeType">点击,登录</button>
                  </div>`,
                methods: {
                    changeType() {
                        logintype = true;
                        alert("用户登录成功");
                    }
                }
            }
            var routes = [
                {"path": "/", component: home},
                {"path": "/about", component: about},
                {"path": "/center", component: center},
                {"path": "/login", component: login},
            ];
            var router = new VueRouter({
                routes
            });
            var logintype = false;
            router.beforeEach((to, from, next) => {
                if (to.path == '/center') {
                    if (logintype) {
                        next();
                    } else {
                        next('/login');
                    }
                } else {
                    next();
                }
            })

            var vm = new Vue({
                el: '#app',
                data: {},
                router
            });
        </script>
    </body>
</html>